<template>
  <div class="app-container">
    <el-button type="primary" size="mini" align="right" @click="handleCreate">新增成品制作</el-button>
    <el-button type="primary" size="mini" align="right" @click=" handleDownload">导出成品制作Excel</el-button>
    <br><br>
    <el-input v-model="search" placeholder="输入成品编号或者名称关键字搜索" size="mini" align="right" width="20%"/>
    <br><br>
    <date></date>
    <el-table
      v-loading="Loading"
      :data="data.filter(data => !search || (data.Name.toLowerCase().includes(search.toLowerCase())||
                                             data.No.toLowerCase().includes(search.toLowerCase())  ||
                                             data.pickerOptions.includes(search)
                                             ))"
      element-loading-text="Loading"
      style="width: 100%">
      <el-table-column label="成品编号" prop="No"/>
      <el-table-column label="成品名称" prop="Name"/>
      <el-table-column label="数量" prop="Quantity"/>
      <el-table-column label="库存" prop="Number"/>
      <el-table-column label="制作人" prop="MakePerson"/>
      <el-table-column :formatter="formatTime" label="登记时间" prop="CreatedAt"/>
    </el-table>
    <!--<el-pagination-->
    <!--:page-size="20"-->
    <!--:pager-count="10"-->
    <!--:total="1000"-->
    <!--align="right"-->
    <!--layout="prev, pager, next"/>-->
    <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="60%">
      <span style="font-size: 14px;font-weight: 700;color: red;font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;margin-left: 8px"> 请选择成品:</span>
      <el-select v-model="selectValue" filterable clearable placeholder="请选择" size="mini" @change="selectChange">
        <el-option
          v-for="item in goods"
          :key="item.ID"
          :label="item.No"
          :value="item"
          :disabled="item.Disabled"/>
      </el-select>
      <el-form v-enterToNext="true" :model="postForm" label-position="left" label-width="110px" size="mini" status-icon>
        <el-form-item>
          <el-table :data="makeData" class="el-table__body" cellspacing="0">
            <el-table-column label="成品编号" prop="ID"/>
            <el-table-column label="成品名称" prop="No"/>
            <el-table-column label="数量" prop="Quantity">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.Quantity" :min="1" size="mini"/>
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="Number"/>
            <el-table-column label="制作人" prop="MakePerson">
              <template slot-scope="scope">
                <el-select v-model="scope.row.MakePerson" filterable clearable placeholder="请选择" size="mini">
                  <el-option
                    v-for="item in persons"
                    :key="item.Name"
                    :label="item.Name"
                    :value="item.Name"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.$index,scope.row)"/>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item align="right">
          <el-button :loading="loading" type="primary" size="meduium" @click="submitForm">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>

import { getCommodities } from '@/api/commodity'
import { getStaff } from '@/api/company'
import { createMakeMsg, getMakeInfo } from '@/api/order'
import { parseTime } from '@/utils'
import date  from  '@/components/date'


export default {
  components: {date},
  data() {
    return {
      data: [],
      selectValue: '',
      goods: [],
      search: '',
      dialogVisible: false,
      dialogTitle: '',
      persons: [],
      makeData: [],
      loading: false,
      totalSize: 2,
      postForm: {
        Goods: []
      },

  }
  },
  created() {
    this.fetchData()
  },
  methods: {
    selectChange() {
      if (this.selectValue !== '') {
        this.selectValue.Disabled = true
        this.makeData.push(this.selectValue)
        this.selectValue = ''
      }
    },
    handleDelete(index, row) {
      this.makeData.splice(index, 1)
      row.Disabled = false
      row.Quantity = 1
      row.MakePerson = ''
      row.Number = 0
    },
    handleAdd(index, row) {

    },
    fetchData() {
      this.Loading = false

      //    TODO  获取成品列表数据方法
      getMakeInfo().then(response => {
        console.log(response)
        this.data = response
        this.Loading = false
      })
      //      获取成品名称方法
      getCommodities().then(response => {
        console.log(response)
        this.goods = response.map(item => {
          return {
            Quantity: 1,
            ID: item.ID,
            No: item.No,
            Name: item.Name,
            MakePerson: '',
            Number:item.Number
          }
        })
      })
      //      获取员工
      getStaff().then(response => {
        console.log(response)
        this.persons = response.map(item => {
          return {
            ID: item.Name,
            Name: item.Name
          }
        })
      })
    },
    handleCreate() {
      this.resetFormData()
      this.dialogTitle = '新增'
      this.dialogVisible = true
      //      this.$nextTick(() => {
      //        this.$refs['postForm'].clearValidate()
      //      })
    },
    handleDownload() {
      this.Loading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['成本编号', '成本名称', '数量','库存', '制作人', '登记时间']
        const filterVal = ['ID', 'Name', 'Quantity', 'Number','MakePerson', 'CreatedAt']
        const list = this.data
        for (var i = 0 ; i < list.length ; i++) {
          list[i].CreatedAt = parseTime(list[i].CreatedAt)
        }
        //        const data = this.formatJson(filterVal, list.filter(data => !this.search || data.Name.toLowerCase().includes(this.search.toLowerCase())))
        const data = this.formatJson(filterVal, list.filter(data => !this.search || (data.Name.toLowerCase().includes(this.search.toLowerCase())) || data.No.toLowerCase().includes(this.search.toLowerCase())))
        //        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '成品制作表'
        })
      })
      this.Loading = false
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    formatTime(row, column) {
      return parseTime(row.CreatedAt)
    },
    resetFormData() {
      for (let i = 0; i < this.goods.length; i++) {
        this.goods[i].Disabled = false
      }
      this.makeData = []
    },
    submitForm() {
      const len = this.makeData.length
      if (len <= 0) {
        this.$message.error('请添加制作信息')
        return
      }
      for (let i = 0; i < len; i++) {
        if (this.makeData[i].Quantity <= 0) {
          this.$message.error('成品数量不能为 0')
          this.postForm.Goods = []
          return
        }
        if (this.makeData[i].MakePerson === '') {
          this.$message.error('制作人不能为空')
          this.postForm.Goods = []
          return
        }
        this.postForm.Goods.push({
          ID: this.makeData[i].ID,
          Name: this.makeData[i].Name,
          MakePerson: this.makeData[i].MakePerson,
          Quantity: this.makeData[i].Quantity,
          Number:this.makeData[i].Number
        })
      }

      console.log(this.postForm)
      this.loading = true
      createMakeMsg(this.postForm)
        .then(response => {
          console.log(response)
          this.loading = false
          this.postForm.Goods = []
          this.$message.success('创建成功')
          this.dialogVisible = false
          this.fetchData()
        })
        .catch((error) => {
          this.loading = false
          this.postForm.Goods = []
          if (error && error.response && error.response.data && error.response.data.error) {
            this.$message.error(error.response.data.error)
          } else {
            this.$message.error('创建失败')
          }
        })
    }

  }
}
</script>
